﻿@model  SDF.Plugin.Misc.DynamicEntity.Models.DESearchModel

@{
    //page title
    ViewBag.Title = T("Plugins.Misc.DynamicEntity.Title").Text;
    //active menu item (system name)
    //Html.SetActiveMenuItemSystemName("DynamicEntity");

    var defaultGridPageSize = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Plugins.Misc.DynamicEntity.Title")
        </h1>
        <div class="pull-right">
            <a href="@Url.Action("Generate")" class="btn bg-blue">
                <i class="fa fa-camera"></i>
                @T("Plugins.Misc.DynamicEntity.GenEntity")
            </a>
            <a href="@Url.Action("Create")" class="btn bg-blue">
                <i class="fa fa-plus-square"></i>
                @T("Admin.Common.AddNew")
            </a>
            <button type="button" id="delete-selected" class="btn bg-red">
                <i class="fa fa-trash-o"></i>
                @T("Admin.Common.Delete.Selected")
            </button>


            <div class="btn-group">
                <button type="button" class="btn btn-success">
                    <i class="fa fa-download"></i>
                    @T("Admin.Common.Export")
                </button>
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button type="submit" name="exportxml-all">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportxml-selected">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.Selected")
                        </button>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <button type="submit" name="exportexcel-all">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportexcel-selected">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.Selected")
                        </button>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(m => m.CodeName)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(m => m.CodeName)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(m => m.Name)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(m => m.Name)
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-7 col-md-offset-5">
                                <button type="button" id="search-entities" class="btn btn-primary btn-search">
                                    <i class="fa fa-search"></i>
                                    @T("Admin.Common.Search")
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div id="entity-grid">
                            <script>
                                $(document).ready(function() {
                                    $("#entity-grid").kendoGrid({
                                        dataSource: {
                                            type: "json",
                                            transport: {
                                                read: {
                                                    url: "@Html.Raw(Url.Action("QueryEntity", "DynamicEntity"))",
                                                    type: "POST",
                                                    dataType: "json",
                                                    data: additionalData
                                                }
                                            },
                                            schema: {
                                                data: "Data",
                                                total: "Total",
                                                errors: "Errors"
                                            },
                                            error: function(e) {
                                                display_kendoui_grid_error(e);
                                                // Cancel the changes
                                                this.cancelChanges();
                                            },
                                            pageSize: @(defaultGridPageSize),
                                            serverPaging: true,
                                            serverFiltering: true,
                                            serverSorting: true
                                        },
                                        pageable: {
                                            refresh: true,
                                            pageSizes: [@(gridPageSizes)]
                                        },
                                        editable: {
                                            confirmation: "@T("Admin.Common.DeleteConfirmation")",
                                            mode: "inline"
                                        },
                                        scrollable: false,
                                        columns: [
                                            {
                                                field: "Id",
                                                headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                                headerAttributes: { style: "text-align:center" },
                                                attributes: { style: "text-align:center" },
                                                template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                                width: 50
                                            },
                                            {
                                                field: "CodeName",
                                                title: "@T("Plugins.Misc.DynamicEntity.CodeName")"
                                            }, {
                                                field: "Name",
                                                title: "@T("Plugins.Misc.DynamicEntity.Name")"
                                            }, {
                                                field: "CreateTimeOnUtc",
                                                title: "@T("Plugins.Misc.DynamicEntity.CreateTimeOnUtc")",
                                                width: 200,
                                                type: "date",
                                                format: "{0:G}"
                                            }, {
                                                field: "Id",
                                                title: " ",
                                                width: 180,
                                                attributes:{
                                                    style:"text-align:center"
                                                },
                                                template: '<a href="EditHeader/#=Id#" class="btn bg-blue"><i class="fa fa-pencil-square-o"></i>@T("Admin.Common.Edit")</a> <span id="header-delete" class="btn bg-red" onclick="doDelete(#=Id#)"><i class="fa fa-trash-o"></i>@T("Admin.Common.Delete")</span>'
                                            }
                                        ]
                                    });
                                });
                            </script>

                            <script type="text/javascript">
                                var selectedIds = [];

                                $(document).ready(function() {
                                    $('#search-entities').click(function() {
                                        var grid = $('#entity-grid').data('kendoGrid');
                                        grid.dataSource.page(1); //new search. Set page size to 1
                                        //grid.dataSource.read(); we already loaded the grid above using "page" function

                                        $('.checkboxGroups').attr('checked', false).change();
                                        selectedIds = [];

                                        return false;
                                    });

                                    $("".concat("#@Html.FieldIdFor(model => model.Name),",
                                    "#@Html.FieldIdFor(model => model.CodeName)")).keydown(function(event) {
                                        if (event.keyCode === 13) {
                                            $("#search-entities").click();
                                            return false;
                                        }
                                    });

                                    $('#mastercheckbox').click(function() {
                                        $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                                    });

                                    //wire up checkboxes.
                                    $('#entity-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function(e) {
                                        var $check = $(this);
                                        if ($check.is(":checked") == true) {
                                            var checked = jQuery.inArray($check.val(), selectedIds);
                                            if (checked == -1) {
                                                //add id to selectedIds.
                                                selectedIds.push($check.val());
                                            }
                                        } else {
                                            var checked = jQuery.inArray($check.val(), selectedIds);
                                            if (checked > -1) {
                                                //remove id from selectedIds.
                                                selectedIds = $.grep(selectedIds, function(item, index) {
                                                    return item != $check.val();
                                                });
                                            }
                                        }
                                        updateMasterCheckbox();
                                    });
                                });

                                function onDataBound(e) {
                                    $('#entity-grid input[type=checkbox][id!=mastercheckbox]').each(function() {
                                        var currentId = $(this).val();
                                        var checked = jQuery.inArray(currentId, selectedIds);
                                        //set checked based on if current checkbox's value is in selectedIds.
                                        $(this).attr('checked', checked > -1);
                                    });

                                    updateMasterCheckbox();
                                }

                                function updateMasterCheckbox() {
                                    var numChkBoxes = $('#entity-grid input[type=checkbox][id!=mastercheckbox]').length;
                                    var numChkBoxesChecked = $('#entity-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
                                    $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                                }

                                function additionalData() {
                                    var data = {
                                        Name: $('#@Html.FieldIdFor(model => model.Name)').val(),
                                        CodeName: $('#@Html.FieldIdFor(model => model.CodeName)').val(),
                                    };
                                    addAntiForgeryToken(data);
                                    return data;
                                }
                            </script>


                            <script>
                                $(function(){
                                    $("#delete-selected").click(function(e){
                                        e.preventDefault();

                                        var postData ={headerIds: selectedIds};
                                        addAntiForgeryToken(postData)

                                        if(selectedIds && selectedIds.length > 0)
                                        {
                                            $.ajax({
                                                url: '/DE/DynamicEntity/DeleteHeaders',
                                                type: 'POST',
                                                async: true,
                                                cache: false,
                                                data: postData,
                                                complete: function(data) {
                                                    //reload grid
                                                    var grid = $('#entity-grid').data('kendoGrid');
                                                    grid.dataSource.page(1); //new search. Set page size to 1
                                                    //grid.dataSource.read(); we already loaded the grid above using "page" function
                                                    //clear selected checkboxes
                                                    $('.checkboxGroups').attr('checked', false).change();
                                                    selectedIds = [];
                                                },
                                                error: function(xhr, ajaxOptions, thrownError) {
                                                    alert(thrownError);
                                                },
                                                traditional: true
                                            });
                                        }
                                        else{
                                            //do noting
                                        }
                                    })
                                });
                            </script>

                            <script>
                                function doDelete(headerId){
                                    if(confirm('@T("Admin.Common.DeleteConfirmation").Text')){
                                        selectedIds.push(headerId);
                                        $("#delete-selected").click();
                                    }
                                    return false;
                                }
                            </script>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
}
